# Title     : TODO
# Objective : TODO
# Created by: Administrator
# Created on: 2019/8/12
library(optparse)
library(magrittr)
library(impute)
library(tidyverse)

option_list <- list(
  make_option("--cc", default = "calculate_config.json", type = "character", help = "config file"),
  make_option("--si", default = "1;0", type = "character", help = "step")
)
opt <- parse_args(OptionParser(option_list = option_list))

args <- commandArgs(trailingOnly = F)
scriptPath <- dirname(sub("--file=", "", args[grep("--file", args)]))
source(str_c(scriptPath, "/base.R"))

configJson <- fromJSON(opt$cc)

si <- opt$si %>%
  str_split(";") %>%
  unlist()
step <- si[1] %>%
  as.numeric()
replaceMethod  <- configJson$datas$replaceMethod[step]
k  <- configJson$datas$knn[step] %>%
  as.numeric()
rate  <- configJson$datas$min[step] %>%
  as.numeric()

data <- read_tsv(str_c(step - 1, ".result.txt")) %>%
  rename(Metabolite = 1) %>%
  mutate_at(vars(-c("Metabolite")), function(x) {
    ifelse(x == 0, NA, x)
  })

if (replaceMethod == "knn") {
  data <- data %>%
    column_to_rownames("Metabolite") %>%
    as.matrix()
  imData <- impute.knn(data, k)
  print("in")
  data <- imData[[1]] %>%
    as.data.frame() %>%
    rownames_to_column("Metabolite") %>%
    as_tibble()
}else if (replaceMethod == "min") {
  onlyData <- data %>%
    select(-"Metabolite")
  minValue <- min(onlyData, na.rm = T)
  data <- data %>%
    mutate_at(vars(-"Metabolite"), function(x) {
      replace_na(x, minValue / rate)
    })
}else if (replaceMethod == "rowMin") {
  onlyData <- data %>%
    select(-"Metabolite")
  minValue <- min(onlyData, na.rm = T)
  data <- data %>%
    rowwise() %>%
    do({
      result <- as_tibble(.)
      data <- result %>% select(-"Metabolite") %>% unlist()
      min <- min(data, na.rm = T)
      trueMin <- if (is.infinite(min)) {
        minValue
      }else min
      result %>% mutate_at(vars(-c("Metabolite")), function(x) {
        replace_na(x, trueMin / rate)
      })
    }) %>%
    ungroup()
}else {
  onlyData <- data %>%
    select(-"Metabolite")
  b <- any(is.na(onlyData))
  if (b) {
    stop("数据中含有缺失值，无法进一步分析！")
  }
}

outData<-data
outData

write_tsv(outData, str_c(step, ".result.txt"))
write_csv(outData, str_c(step, ".na_fill.csv"))








